<template>
  <van-cell-group title="当前定位城市">
    <van-cell :title="guessCity.name" is-link @click="handleGuess" />
  </van-cell-group>
  <van-cell-group title="热门城市">
    <van-grid>
      <template v-for="item of hotcity" :key="item.id">
        <van-grid-item
          :text="item.name"
          @click="handleHot(item)"
        ></van-grid-item>
      </template>
    </van-grid>
  </van-cell-group>
  <van-index-bar :index-list="indexList">
    <template v-for="key of indexList" :key="key">
      <van-index-anchor :index="key" />
      <template v-for="item of citys[key]" :key="item.id">
        <van-cell :title="item.name" @click="handleCitys(item)" />
      </template>
    </template>
  </van-index-bar>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

export default defineComponent({
  setup() {
    const store = useStore();
    const router = useRouter();
    const state: any = reactive({
      guessCity: store.getters.guesscity,
      hotcity: store.getters.hotcity,
      citys: store.getters.citys,
      indexList: [],
    });
    const getIndexList = () => {
      let anchor = [];
      for (let city in state.citys) {
        anchor.push(city);
      }
      state.indexList = anchor.sort();
      console.log(state.indexList);
    };
    const handleGuess = () => {
      store.dispatch("GenarateCityId", state.guessCity.id);
      router.push({
        path: "/address/search",
        query: { cityname: state.guessCity.name },
      });
    };
    const handleHot = ({ id, name }: any) => {
      store.dispatch("GenarateCityId", id);
      router.push({ path: "/address/search", query: { cityname: name } });
    };
    const handleCitys = ({ id, name }: any) => {
      store.dispatch("GenarateCityId", id);
      router.push({ path: "/address/search", query: { cityname: name } });
    };
    getIndexList();
    onMounted(() => {
      store.dispatch("GetCitys");
      store.dispatch("GetGuessCity");
      store.dispatch("GetHotCity");
      console.log(state);
    });

    return {
      ...toRefs(state),
      handleGuess,
      handleHot,
      handleCitys,
    };
  },
});
</script>

<style scoped>
</style>